package com.easy.module.generator.controller;

import com.easy.framework.common.model.R;
import com.easy.framework.common.utils.ConvertUtil;
import com.easy.framework.common.validate.Update;
import com.easy.framework.database.page.Pagination;
import com.easy.framework.poi.utils.ExcelUtils;
import com.easy.framework.web.base.BaseController;
import com.easy.module.generator.entity.GenTable;
import com.easy.module.generator.entity.GenTableField;
import com.easy.module.generator.model.CodeModel;
import com.easy.module.generator.query.GenTableFieldQuery;
import com.easy.module.generator.query.GenTableQuery;
import com.easy.module.generator.service.IGenTableFieldService;
import com.easy.module.generator.service.IGenTableService;
import com.easy.module.log.annotation.Log;
import com.easy.module.log.enums.Operation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RequiredArgsConstructor
@RequestMapping("/generator/table")
@RestController
public class GenTableController extends BaseController {

    final IGenTableService genTableService;

    final IGenTableFieldService genTableFieldService;

    @PreAuthorize("@perm.hasPermission('gen$list')")
    @GetMapping("/page")
    public R<Pagination<GenTable>> page(GenTableQuery query) {
        return R.success(genTableService.page(query));
    }

    @Log(title = "生成表管理", type = Operation.EXPORT)
    @PreAuthorize("@perm.hasPermission('gen$export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, GenTableQuery query) throws IOException {
        List<GenTable> list = genTableService.list(query);
        ExcelUtils.exportExcel(response, list, "生成表管理");
    }

    /**
     * 修改
     */
    @PreAuthorize("@perm.hasPermission('gen$edit')")
    @Log(title = "生成表管理", type = Operation.UPDATE)
    @PutMapping
    public R edit(@Validated({Update.class}) @RequestBody GenTable model) {
        return R.result(genTableService.updateById(model));
    }


    @PreAuthorize("@perm.hasPermission('gen$remove')")
    @Log(title = "生成表管理", type = Operation.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable("ids") Long[] ids) {
        return R.result(genTableService.deleteByIds(List.of(ids)));
    }

    /**
     * 查询数据库列表
     */
    @PreAuthorize("@perm.hasPermission('gen$import')")
    @GetMapping("/db/page")
    public R<Pagination<GenTable>> listDbTable(GenTableQuery query) {
        return R.success(genTableService.page(query, () -> genTableService.listDbTable(query)));
    }

    /**
     * 导入表结构（保存）
     */
    @PreAuthorize("@perm.hasPermission('gen$import')")
    @Log(title = "生成表管理", type = Operation.IMPORT)
    @PostMapping("/db/import")
    public R importDbTable(@RequestBody List<GenTable> tables) {
        genTableService.importDbTable(tables);
        return R.success();
    }

    /**
     * 下载代码
     */
    @PreAuthorize("@perm.hasPermission('gen$edit')")
    @GetMapping("/db/synch/{tableId}")
    public R synchDbTable(@PathVariable(name = "tableId") Long tableId) {
        genTableService.synchDbTable(tableId);
        return R.success();
    }


    /**
     * 预览代码
     */
    @PreAuthorize("@perm.hasPermission('gen$preview')")
    @GetMapping("/preview/{tableId}")
    public R<List<CodeModel>> preview(@PathVariable("tableId") Long tableId) {
        return R.success(genTableService.generatorCode(List.of(tableId)));
    }

    /**
     * 下载代码
     */
    @PreAuthorize("@perm.hasAnyPermission('gen$preview','gen$download')")
    @GetMapping("/download")
    public void download(HttpServletResponse response, @RequestParam(value = "ids", required = true) Long[] ids) throws IOException {
        byte[] bytes = genTableService.download(List.of(ids));
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"easy.zip\"");
        response.addHeader("Content-Length", "" + bytes.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(bytes, response.getOutputStream());
    }



    @PreAuthorize("@perm.hasPermission('gen$edit')")
    @GetMapping("/field/list")
    public R<List<GenTableField>> listField(GenTableFieldQuery query) {
        return R.success(genTableFieldService.list(query));
    }


    /**
     * 修改
     */
    @PreAuthorize("@perm.hasPermission('gen$edit')")
    @Log(title = "生成表字段管理", type = Operation.UPDATE)
    @PutMapping("/field")
    public R edit(@Validated({Update.class}) @RequestBody GenTableField genTableField) {
        return R.result(genTableFieldService.updateById(genTableField));
    }
}
